package jp.team.nature.reizoukoapp;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import jp.team.nature.reizoukoapp.constant.Constant;
import jp.team.nature.reizoukoapp.db.SQLOpenHelper;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class NyuuryokuActivity extends Activity implements OnClickListener {

    private static final String ZAIKO_TABLE = "zaiko_table";
	private static final String DATE_FORMAT = "yyyy/MM/dd";
	private static final String MESSAGE_TOUROKU = "登録しました";

	private InputMethodManager inputMethodManager;

	private DatePickerDialog.OnDateSetListener dateSetListner;

	private AutoCompleteTextView categoryView;
	private AutoCompleteTextView nameView;
	private EditText quantityView;
	private EditText expDateView;
	private Spinner unitView;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.activity_nyuuryoku);

    	// ボタンにリスナ登録
    	Button registButton = (Button) findViewById(R.id.button1);
    	Button backButton = (Button) findViewById(R.id.button2);
    	Button clearButton = (Button) findViewById(R.id.button3);
    	Button kakuninButton = (Button) findViewById(R.id.button4);

    	registButton.setOnClickListener(this);
    	backButton.setOnClickListener(this);
    	clearButton.setOnClickListener(this);
    	kakuninButton.setOnClickListener(this);

    	// 初期状態ではボタンクリック不可
    	registButton.setEnabled(false);

    	categoryView = (AutoCompleteTextView) findViewById(R.id.inputCategory);
    	nameView = (AutoCompleteTextView) findViewById(R.id.inputName);
    	quantityView = (EditText) findViewById(R.id.inputQuantity);
    	expDateView = (EditText) findViewById(R.id.inputExpDate);
    	unitView = (Spinner) findViewById(R.id.spinnerQuantity);

    	// 入力候補表示
    	ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(this, R.layout.list_item, Constant.CATEGORIES);
    	categoryView.setAdapter(categoryAdapter);
    	categoryView.setCompletionHint("分類");
    	categoryView.setThreshold(1);
    	categoryView.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				// キーボード閉じる
				return false;
			}
		});
    	// タップした瞬間は反応しないのでLisnterで強制的に表示
//    	categoryView.setOnFocusChangeListener(new OnFocusChangeListener() {
//			@Override
//			public void onFocusChange(View v, boolean hasFocus) {
//				if (hasFocus) {
//					categoryView.showDropDown();
//				}
//			}
//		});
    	// タップでも反応
    	categoryView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				categoryView.showDropDown();
			}
		});

    	ArrayAdapter<String> nameAdapter = new ArrayAdapter<String>(this, R.layout.list_item, Constant.MEATS);
    	nameView.setAdapter(nameAdapter);
    	nameView.setThreshold(1);
    	nameView.setCompletionHint("食品名");
    	// 以下ボタンの有効/無効化処理
    	// 3つ用意したものの多分onFocusChangedだけでいけそうな気がする
    	// とりあえず動いてしまったので放置
    	nameView.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				Button b = (Button) findViewById(R.id.button1);
				EditText quantity = (EditText) findViewById(R.id.inputQuantity);
				if (! v.getText().toString().equals("")) {
					if (!(quantity.getText().toString().equals(""))
							&& (Float.valueOf((quantity.getText().toString())) > 0)) {
						// 何らかの入力がされていればボタンを有効化
						b.setEnabled(true);
					}  else {
						b.setEnabled(false);
					}
				} else {
					b.setEnabled(false);
				}
				// キーボード閉じる
				return false;
			}
		});
    	nameView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Button b = (Button) findViewById(R.id.button1);
				EditText quantity = (EditText) findViewById(R.id.inputQuantity);
				if (!(quantity.getText().toString().equals(""))
						&& (Float.valueOf((quantity.getText().toString())) > 0)) {
					// 何らかの入力がされていればボタンを有効化
					b.setEnabled(true);
				} else {
					b.setEnabled(false);
				}
			}
		});
    	nameView.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				AutoCompleteTextView input = (AutoCompleteTextView) v;
				Button b = (Button) findViewById(R.id.button1);
				EditText quantity = (EditText) findViewById(R.id.inputQuantity);
				if (! input.getText().toString().equals("")) {
					if (!(quantity.getText().toString().equals(""))
							&& (Float.valueOf((quantity.getText().toString())) > 0)) {
						// 何らかの入力がされていればボタンを有効化
						b.setEnabled(true);
					} else {
						b.setEnabled(false);
					}
				} else {
					b.setEnabled(false);
				}
			}
		});

    	// タップでも反応
    	nameView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ArrayAdapter<String> adapter;
				String[] array = {};
				String category = (String) categoryView.getText().toString();
				if (category.equals("肉")) {
					array = Constant.MEATS;
				} else if (category.equals("野菜")) {
					array = Constant.VEGITABLES;
				} else if (category.equals("魚介類")) {
					array = Constant.FISH;
				} else if (category.equals("乳製品")) {
					array = Constant.DAILY;
				} else if (category.equals("卵")) {
					array = Constant.EGG;
				} else if (category.equals("きのこ")) {
					array = Constant.MUSHROOM;
				} else if (category.equals("果物")) {
					array = Constant.FRUIT;
				} else if (category.equals("麺類")) {
					array = Constant.NOODLE;
				}
				adapter = new ArrayAdapter<String>(NyuuryokuActivity.this, R.layout.list_item, array);
				nameView.setAdapter(adapter);
		    	nameView.setThreshold(1);
		    	nameView.setCompletionHint("食品名");

				nameView.showDropDown();
			}
		});

    	quantityView.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				TextView input = (TextView) v;
				TextView name = (AutoCompleteTextView) findViewById(R.id.inputName);
				Button b = (Button) findViewById(R.id.button1);
				if (!(input.getText().toString().equals("")) && !(name.getText().toString().equals(""))) {
					// 何らかの入力がされていればボタンを有効化
					if (Float.valueOf(input.getText().toString()) > 0) {
						b.setEnabled(true);
					} else {
						b.setEnabled(false);
					}
				} else {
					b.setEnabled(false);
				}
			}
		});
    	quantityView.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				TextView input = (TextView) v;
				Button b = (Button) findViewById(R.id.button1);
				TextView name = (AutoCompleteTextView) findViewById(R.id.inputName);
				if (!(input.getText().toString().equals("")) && !(name.getText().toString().equals(""))) {
					// 何らかの入力がされていればボタンを有効化
					if (Float.valueOf(input.getText().toString()) > 0) {
						b.setEnabled(true);
					} else {
						b.setEnabled(false);
					}
				} else {
					b.setEnabled(false);
				}
				// キーボード閉じる
				return false;
			}
		});

    	// focus指定
    	categoryView.setNextFocusDownId(R.id.inputName);
    	nameView.setNextFocusDownId(R.id.inputQuantity);
    	quantityView.setNextFocusDownId(R.id.inputExpDate);

    	// キーボード閉じる
    	// todo:未使用になるかも
    	inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    	expDateView.setOnKeyListener(new OnKeyListener() {
    		//コールバックとしてonKey()メソッドを定義
    		@Override
    		public boolean onKey(View v, int keyCode, KeyEvent event) {
    		//イベントを取得するタイミングには、ボタンが押されてなおかつエンターキーだったときを指定
    		if((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)){
    		//キーボードを閉じる
    		inputMethodManager.hideSoftInputFromWindow(
    				expDateView.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
    		return true;
    		}
    		return false;
    		}
		});

    	// DatePicker表示
    	dateSetListner = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				expDateView.setText(year + "/" + (monthOfYear + 1) + "/" + dayOfMonth);
			}
		};

		expDateView.setOnClickListener(new OnClickListener() {
    		// DatePicker表示
			@Override
			public void onClick(View v) {
			Calendar calendar = Calendar.getInstance();
				DatePickerDialog dialog =
						new DatePickerDialog(NyuuryokuActivity.this, dateSetListner,
								calendar.get(Calendar.YEAR),
								calendar.get(Calendar.MONTH),
								calendar.get(Calendar.DAY_OF_MONTH));
				dialog.show();
			}
		});
	}

    @SuppressLint("SimpleDateFormat")
	public void onClick(View v) {
    	if (v == findViewById(R.id.button1)) {
    		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
    		SQLOpenHelper helper = new SQLOpenHelper(this);
    		SQLiteDatabase db = helper.getReadableDatabase();

    		// 購入日（今日）取得
    		String today = sdf.format(new Date());
    		ContentValues cv = new ContentValues();

    		String categoryText = categoryView.getText().toString();
    		String nameText = nameView.getText().toString();
    		String quantityText = quantityView.getText().toString();
    		String expDateText = expDateView.getText().toString();
    		String unitText = unitView.getSelectedItem().toString();

            cv.put("category", categoryText);
            cv.put("name", nameText);
            cv.put("quantity", quantityText);
            cv.put("buydate", today);
            cv.put("expdate", expDateText);
            cv.put("unit", unitText);
            db.insert(ZAIKO_TABLE, null, cv);

            // db閉じる
            db.close();
            // テキストクリア
            clearText();
            // ボタンの再度無効化
            v.setEnabled(false);
            // Toastで登録にユーザ通知
            Toast.makeText(this, MESSAGE_TOUROKU, Toast.LENGTH_LONG).show();
    	}
    	if (v == findViewById(R.id.button2)) {
    		finish();
    	}
    	if (v == findViewById(R.id.button3)) {
    		clearText();
    	}
    	if (v == findViewById(R.id.button4)) {
			Intent intent = new Intent();
			intent.setClassName("jp.team.nature.reizoukoapp", "jp.team.nature.reizoukoapp.ZaikoKakuninActivity");
			startActivity(intent);
    	}
    }

    private void clearText() {
    	categoryView.setText("");
		nameView.setText("");
		quantityView.setText("");
		expDateView.setText("");
    }
}